import rclpy
from rclpy.node import Node
from chapt4_interfaces.srv import FaceDetector
from ament_index_python.packages import get_package_share_directory
from cv_bridge import CvBridge
from sensor_msgs.msg import Image
import cv2
import face_recognition
import time
class FaceDectorClientNode(Node):
    def __init__(self):
        super().__init__('face_detect_client')
        self.client_=self.create_client(FaceDetector,'/face_detect')
        self.bridge=CvBridge()
        self.test1_image_path=get_package_share_directory(
        'demo_python_service') + '/resource/trump.jpeg'
        self.image=cv2.imread(self.test1_image_path)
        self.get_logger().info("begin!")
    def send_request(self):
        while self.client_.wait_for_service(timeout_sec=1.0) is False:
            self.get_logger().info(f'wait......')
        request=FaceDetector.Request()
        request.image=self.bridge.cv2_to_imgmsg(self.image)
        future=self.client_.call_async(request)
        rclpy.spin_until_future_complete(self,future)
        response=future.result()
        self.get_logger().info(f'recieve:{response.number} faces,spend{response.use_time} s')
        self.show_face_location(response)
    def show_face_location(self,response):
        for i in range(response.number):
            top=response.top[i]
            right=response.right[i]
            bottom=response.bottom[i]
            left=response.left[i]
            cv2.rectangle(self.image,(left,top),(right,bottom),(255,0,0),2)
            cv2.imshow('Face_Detection_Resuilt',self.image)
            cv2.waitKey(0)
        
        
def main():
    rclpy.init()
    node=FaceDectorClientNode()
    node.send_request()
    rclpy.spin(node)
    rclpy.shutdown()